package middle;

public class Solution_24 {

    /*public ListNode swapPairs(ListNode head) {
        ListNode header1 = null, node1 = null;
        ListNode header2 = null, node2 = null;
        boolean flag = true; // true:奇数
        ListNode node = head;
        while (node != null) {
            if (flag) {
                if (node1 == null) {
                    node1 = node;
                    header1 = node1;
                } else {
                    node1.next = node;
                    node1 = node;
                }
                node = node.next;
                node1.next = null;
            } else {
                if (node2 == null) {
                    node2 = node;
                    header2 = node2;
                } else {
                    node2.next = node;
                    node2 = node;
                }
                node = node.next;
                node2.next = null;
            }
            flag = !flag;
        }
        flag = false;
        ListNode rst = null;
        while (header1 != null || header2 != null) {
            if (flag && header1 != null) {
                if (node == null) {
                    node = header1;
                    rst = node;
                } else {
                    node.next = header1;
                    node = node.next;
                }
                header1 = header1.next;
            } else if (!flag && header2 != null) {
                if (node == null) {
                    node = header2;
                    rst = node;
                } else {
                    node.next = header2;
                    node = node.next;
                }
                header2 = header2.next;
            }
            flag = !flag;
        }
        return rst;
    }
*/
    public ListNode swapPairs(ListNode head) {
        ListNode one = null, two = null;
        if (head != null) {
            one = head;
            head = head.next;
        }
        if (head != null) {
            two = head;
            head = head.next;
        }
        if (two != null) {
            two.next = one;
            one.next = swapPairs(head);
            return two;
        } else {
            return one;
        }
    }

    public static void main(String[] args) {
        Solution_24 model = new Solution_24();
        ListNode header = new ListNode(1);
        header.next = new ListNode(2);
        header.next.next = new ListNode(3);
        header.next.next.next = new ListNode(4);
        header.next.next.next.next = new ListNode(5);
        ListNode node = model.swapPairs(header);
        System.out.println(node);
    }

    static class ListNode {

        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
